package com.greate.community.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.List;

/**
 * 跨域配置类
 */
@Slf4j
//@Profile({"produce", "test"})
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class HttpCorsFilter extends CorsFilter {

    private static List<String> allowedOrigins;

    public HttpCorsFilter(Environment environment) {
        super(configurationSource(environment));
    }

    private static UrlBasedCorsConfigurationSource configurationSource(Environment environment) {
        String allowedOriginsStr = environment.getProperty("spring.cors.allowedOrigins");

        CorsConfiguration corsConfig = new CorsConfiguration();
        List<String> allowedHeaders = Arrays.asList("Authorization", "content-type", "X-Requested-With", "XMLHttpRequest");
        List<String> exposedHeaders = Arrays.asList("Authorization", "content-type", "X-Requested-With", "XMLHttpRequest");
        List<String> allowedMethods = Arrays.asList("POST", "GET", "DELETE", "PUT", "OPTIONS");
//        List<String> allowedOriginPatterns = Arrays.asList("*");
        corsConfig.setAllowedHeaders(allowedHeaders);
        corsConfig.setAllowedMethods(allowedMethods);
        if (StringUtils.isNotEmpty(allowedOriginsStr)) {
            allowedOrigins = Arrays.asList(allowedOriginsStr.split(","));
            log.info("spring.cors.allowedOrigins: {}", allowedOrigins);
            corsConfig.setAllowedOrigins(allowedOrigins);
        }
        corsConfig.setExposedHeaders(exposedHeaders);
//        corsConfig.setAllowedOriginPatterns(allowedOriginPatterns);
        corsConfig.setMaxAge(36000L);
        corsConfig.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfig);
        return source;
    }

}
